<template>
  <div class="order-form">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      :disabled="mode === 'view'"
    >
      <!-- 基本信息 -->
      <el-card class="form-section" header="基本信息">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单编号" prop="orderNo">
              <el-input v-model="formData.orderNo" placeholder="系统自动生成" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customerId">
              <el-select v-model="formData.customerId" placeholder="请选择客户" style="width: 100%">
                <el-option
                  v-for="customer in customers"
                  :key="customer.id"
                  :label="customer.name"
                  :value="customer.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="下单日期" prop="orderDate">
              <el-date-picker
                v-model="formData.orderDate"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交货日期" prop="deliveryDate">
              <el-date-picker
                v-model="formData.deliveryDate"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="销售员" prop="salesperson">
              <el-select v-model="formData.salesperson" placeholder="请选择销售员" style="width: 100%">
                <el-option label="张三" value="张三" />
                <el-option label="李四" value="李四" />
                <el-option label="王五" value="王五" />
                <el-option label="赵六" value="赵六" />
                <el-option label="孙七" value="孙七" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="待审核" value="pending" />
                <el-option label="已审核" value="approved" />
                <el-option label="生产中" value="producing" />
                <el-option label="待发货" value="ready" />
                <el-option label="已发货" value="shipped" />
                <el-option label="已完成" value="completed" />
                <el-option label="已取消" value="cancelled" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 商品明细 -->
      <el-card class="form-section" header="商品明细">
        <div class="product-actions">
          <el-button type="primary" size="small" @click="handleAddProduct" v-if="mode !== 'view'">
            <el-icon><Plus /></el-icon>
            添加商品
          </el-button>
        </div>
        <el-table :data="formData.products" border stripe>
          <el-table-column prop="productName" label="商品名称" width="200">
            <template #default="{ row, $index }">
              <el-select
                v-if="mode !== 'view'"
                v-model="row.productId"
                placeholder="选择商品"
                @change="handleProductChange(row, $index)"
                style="width: 100%"
              >
                <el-option
                  v-for="product in products"
                  :key="product.id"
                  :label="product.name"
                  :value="product.id"
                />
              </el-select>
              <span v-else>{{ row.productName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="specification" label="规格" width="120" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="quantity" label="数量" width="120">
            <template #default="{ row, $index }">
              <el-input-number
                v-if="mode !== 'view'"
                v-model="row.quantity"
                :min="1"
                @change="calculateRowTotal(row, $index)"
                style="width: 100%"
              />
              <span v-else>{{ row.quantity }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="unitPrice" label="单价" width="120">
            <template #default="{ row, $index }">
              <el-input-number
                v-if="mode !== 'view'"
                v-model="row.unitPrice"
                :min="0"
                :precision="2"
                @change="calculateRowTotal(row, $index)"
                style="width: 100%"
              />
              <span v-else>¥{{ row.unitPrice }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="discount" label="折扣(%)" width="100">
            <template #default="{ row, $index }">
              <el-input-number
                v-if="mode !== 'view'"
                v-model="row.discount"
                :min="0"
                :max="100"
                @change="calculateRowTotal(row, $index)"
                style="width: 100%"
              />
              <span v-else>{{ row.discount }}%</span>
            </template>
          </el-table-column>
          <el-table-column prop="totalPrice" label="小计" width="120">
            <template #default="{ row }">
              <span class="amount">¥{{ row.totalPrice?.toLocaleString() || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" v-if="mode !== 'view'">
            <template #default="{ $index }">
              <el-button
                type="danger"
                size="small"
                @click="handleRemoveProduct($index)"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 合计信息 -->
        <div class="total-section">
          <el-row :gutter="20">
            <el-col :span="18">
              <div class="total-info">
                <span>商品总数量: <strong>{{ totalQuantity }}</strong></span>
                <span>商品总金额: <strong class="amount">¥{{ totalAmount.toLocaleString() }}</strong></span>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-card>

      <!-- 其他信息 -->
      <el-card class="form-section" header="其他信息">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="付款方式" prop="paymentMethod">
              <el-select v-model="formData.paymentMethod" placeholder="请选择付款方式" style="width: 100%">
                <el-option label="现金" value="cash" />
                <el-option label="银行转账" value="transfer" />
                <el-option label="支票" value="check" />
                <el-option label="信用证" value="credit" />
                <el-option label="月结" value="monthly" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运输方式" prop="shippingMethod">
              <el-select v-model="formData.shippingMethod" placeholder="请选择运输方式" style="width: 100%">
                <el-option label="自提" value="pickup" />
                <el-option label="物流配送" value="logistics" />
                <el-option label="快递" value="express" />
                <el-option label="专车配送" value="dedicated" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="收货地址" prop="deliveryAddress">
              <el-input
                v-model="formData.deliveryAddress"
                type="textarea"
                :rows="2"
                placeholder="请输入详细的收货地址"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="formData.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
    </el-form>

    <!-- 操作按钮 -->
    <div class="form-actions" v-if="mode !== 'view'">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSave" :loading="saving">
        {{ mode === 'add' ? '创建订单' : '更新订单' }}
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'

// Props
const props = defineProps({
  orderData: {
    type: Object,
    default: null
  },
  mode: {
    type: String,
    default: 'add', // add, edit, view
    validator: (value) => ['add', 'edit', 'view'].includes(value)
  }
})

// Emits
const emit = defineEmits(['save', 'cancel'])

// 响应式数据
const formRef = ref()
const saving = ref(false)

// 表单数据
const formData = reactive({
  id: null,
  orderNo: '',
  customerId: '',
  customerName: '',
  orderDate: '',
  deliveryDate: '',
  salesperson: '',
  status: 'pending',
  paymentMethod: '',
  shippingMethod: '',
  deliveryAddress: '',
  remark: '',
  products: [],
  totalAmount: 0,
  quantity: 0
})

// 表单验证规则
const formRules = {
  customerId: [{ required: true, message: '请选择客户', trigger: 'change' }],
  orderDate: [{ required: true, message: '请选择下单日期', trigger: 'change' }],
  deliveryDate: [{ required: true, message: '请选择交货日期', trigger: 'change' }],
  salesperson: [{ required: true, message: '请选择销售员', trigger: 'change' }],
  paymentMethod: [{ required: true, message: '请选择付款方式', trigger: 'change' }],
  shippingMethod: [{ required: true, message: '请选择运输方式', trigger: 'change' }],
  deliveryAddress: [{ required: true, message: '请输入收货地址', trigger: 'blur' }]
}

// 客户列表
const customers = ref([
  { id: 1, name: '华润万家', address: '深圳市南山区华润城' },
  { id: 2, name: '沃尔玛', address: '北京市朝阳区沃尔玛总部' },
  { id: 3, name: '家乐福', address: '上海市浦东新区家乐福中国总部' },
  { id: 4, name: '大润发', address: '江苏省南京市大润发总部' },
  { id: 5, name: '永辉超市', address: '福建省福州市永辉总部' }
])

// 商品列表
const products = ref([
  { id: 1, name: '苹果', specification: '红富士', unit: '箱', price: 120 },
  { id: 2, name: '香蕉', specification: '进口', unit: '箱', price: 80 },
  { id: 3, name: '橙子', specification: '脐橙', unit: '箱', price: 100 },
  { id: 4, name: '葡萄', specification: '巨峰', unit: '箱', price: 150 },
  { id: 5, name: '草莓', specification: '奶油草莓', unit: '箱', price: 200 },
  { id: 6, name: '西瓜', specification: '无籽', unit: '个', price: 25 },
  { id: 7, name: '芒果', specification: '台农', unit: '箱', price: 180 },
  { id: 8, name: '猕猴桃', specification: '绿心', unit: '箱', price: 160 }
])

// 计算属性
const totalQuantity = computed(() => {
  return formData.products.reduce((sum, item) => sum + (item.quantity || 0), 0)
})

const totalAmount = computed(() => {
  return formData.products.reduce((sum, item) => sum + (item.totalPrice || 0), 0)
})

// 方法
const handleAddProduct = () => {
  formData.products.push({
    productId: '',
    productName: '',
    specification: '',
    unit: '',
    quantity: 1,
    unitPrice: 0,
    discount: 0,
    totalPrice: 0
  })
}

const handleRemoveProduct = (index) => {
  formData.products.splice(index, 1)
}

const handleProductChange = (row, index) => {
  const product = products.value.find(p => p.id === row.productId)
  if (product) {
    row.productName = product.name
    row.specification = product.specification
    row.unit = product.unit
    row.unitPrice = product.price
    calculateRowTotal(row, index)
  }
}

const calculateRowTotal = (row, index) => {
  const quantity = row.quantity || 0
  const unitPrice = row.unitPrice || 0
  const discount = row.discount || 0
  
  row.totalPrice = quantity * unitPrice * (1 - discount / 100)
}

const handleSave = async () => {
  try {
    await formRef.value.validate()
    
    if (!formData.products.length) {
      ElMessage.warning('请至少添加一个商品')
      return
    }
    
    // 验证商品信息
    for (let i = 0; i < formData.products.length; i++) {
      const product = formData.products[i]
      if (!product.productId) {
        ElMessage.warning(`请选择第${i + 1}行的商品`)
        return
      }
      if (!product.quantity || product.quantity <= 0) {
        ElMessage.warning(`请输入第${i + 1}行的有效数量`)
        return
      }
      if (!product.unitPrice || product.unitPrice <= 0) {
        ElMessage.warning(`请输入第${i + 1}行的有效单价`)
        return
      }
    }
    
    // 更新总计信息
    formData.totalAmount = totalAmount.value
    formData.quantity = totalQuantity.value
    
    // 获取客户名称
    const customer = customers.value.find(c => c.id === formData.customerId)
    if (customer) {
      formData.customerName = customer.name
    }
    
    saving.value = true
    emit('save', { ...formData })
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const handleCancel = () => {
  emit('cancel')
}

const initFormData = () => {
  if (props.orderData) {
    Object.assign(formData, props.orderData)
    if (!formData.products) {
      formData.products = []
    }
  } else {
    // 新增模式，设置默认值
    formData.orderDate = new Date().toISOString().split('T')[0]
    const deliveryDate = new Date()
    deliveryDate.setDate(deliveryDate.getDate() + 7)
    formData.deliveryDate = deliveryDate.toISOString().split('T')[0]
    formData.products = []
  }
}

// 监听器
watch(() => props.orderData, () => {
  initFormData()
}, { immediate: true })

watch(() => props.mode, (newMode) => {
  if (newMode === 'add') {
    saving.value = false
  }
})

// 生命周期
onMounted(() => {
  initFormData()
})
</script>

<style scoped>
.order-form {
  max-height: 70vh;
  overflow-y: auto;
}

.form-section {
  margin-bottom: 20px;
}

.product-actions {
  margin-bottom: 16px;
}

.total-section {
  margin-top: 16px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.total-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total-info span {
  font-size: 14px;
  color: #606266;
}

.amount {
  color: #E6A23C;
  font-weight: 600;
}

.form-actions {
  margin-top: 20px;
  text-align: right;
  padding-top: 20px;
  border-top: 1px solid #EBEEF5;
}

.form-actions .el-button {
  margin-left: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .order-form {
    max-height: 60vh;
  }
  
  .total-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .form-actions {
    text-align: center;
  }
  
  .form-actions .el-button {
    margin: 0 6px;
  }
}
</style>